package com.sixbro.authorization.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/15 17:26
 */
public class ClientDetailsServiceImpl implements ClientDetailsService {

    private Map<String, BaseClientDetails> clientDetailsMap = new HashMap<>();

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    public void init() {
        String clientSecret = passwordEncoder.encode("123456");
        BaseClientDetails client = new BaseClientDetails();
        // 客户端id
        client.setClientId("client");
        // 客户端密码
        client.setClientSecret(clientSecret);
        // 客户端授权类型(authorization_code:授权码类型 password:密码类型 implicit:简化类型/隐式类型 client_credentials:客户端类型 refresh_token:该为特例，加了才可以刷新授权)
        client.setAuthorizedGrantTypes(Arrays.asList("password", "refresh_token"));
        client.setAccessTokenValiditySeconds(3600 * 24);
        client.setRefreshTokenValiditySeconds(3600 * 24 * 7);
        client.setScope(Arrays.asList("all"));
        client.setAuthorities(AuthorityUtils.NO_AUTHORITIES);
        client.isAutoApprove(Boolean.TRUE.toString());
        clientDetailsMap.put("client", client);

        BaseClientDetails app = new BaseClientDetails();
        app.setClientId("app");
        app.setClientSecret(clientSecret);
        app.setAuthorizedGrantTypes(Arrays.asList("password", "refresh_token"));
        app.setAccessTokenValiditySeconds(3600 * 24);
        app.setRefreshTokenValiditySeconds(3600 * 24 * 7);
        app.setScope(Arrays.asList("all"));
        app.setAuthorities(AuthorityUtils.NO_AUTHORITIES);
        client.isAutoApprove(Boolean.TRUE.toString());
        clientDetailsMap.put("app", app);
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        ClientDetails details = clientDetailsMap.get(clientId);
        if (details == null) {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
        return details;
    }
}
